<template>
    <div class="bill-of-quantities">
        <div class="handle-button">
            <BaseButton v-if="(type === 1 && premissionCode.has('dlyh_e6_f5_2')) || (type === 2 && premissionCode.has('dlyh_e7_f14_2'))" :disabled="isLock" @click="handleImport">导入</BaseButton>
            <BaseButton v-if="(type === 1 && premissionCode.has('dlyh_e6_f6_2')) || (type === 2 && premissionCode.has('dlyh_e7_f15_2'))" :loading="exportLoading" type="second" @click="handleExport">导出</BaseButton>
            <BaseButton v-if="(type === 1 && premissionCode.has('dlyh_e6_f7_2')) || (type === 2 && premissionCode.has('dlyh_e7_f16_2'))" type="second" @click="checkDeleteList">已删除清单</BaseButton>
        </div>

        <div class="bill-of-quantities-content">
            <div class="left">
                <TitleTips :title="leftTitle">
                    <div v-if="type === 1 && !isLock && premissionCode.has('dlyh_e29_f28_2')" slot="button" style="position: absolute; right: 0; font-size: 18px; cursor: pointer;" @click="handleAddChapter">
                        <i class="el-icon-s-tools"></i>
                    </div>
                </TitleTips>
                <div v-if="chapterList.length > 0" v-loading="schemeLoading" class="list">
                    <div
                        v-for="item in chapterList"
                        :key="item.code"
                        class="item"
                        :class="{ active: chapterCode === item.code}"
                        @click="handleChangeScheme(item)"
                    >
                        <span class="name g-line-1">{{ item.name }}</span>
                        
                        <!-- 属于工程量清单，且未锁定时，才显示设置按钮 -->
                        <div v-if="type === 1 && !isLock && premissionCode.has('dlyh_e29_f28_2')" class="btn">
                            <BaseButton type="text" color="danger" @click.stop="handleDeleteChapter(item.id, item.code)">删除</BaseButton>
                        </div>
                    </div>
                </div>
                <div v-else class="no-data">
                    <IconSvg icon-class="no-data2" class="icon"></IconSvg>
                    <span v-if="isLock || type === 2 || !premissionCode.has('dlyh_e29_f28_2')">暂无数据</span>
                    <!-- 没锁定时候，才能显示配置章次 -->
                    <span v-if="type === 1 && !isLock && premissionCode.has('dlyh_e29_f28_2')">暂无数据，<i class="button" @click="handleAddChapter">配置章次</i></span>
                </div>
            </div>
            <BasePage style="flex: 1;">
                <TitleTips slot="title" :title="activeTitleName || rightitle">
                    <template v-if="activeTitleName && totalAmount">
                        <span slot="other" style="font-weight: normal;color: #44444F;">（合计：<i class="color-blue" style="font-style: normal;">￥{{ totalAmount }}</i>）</span>
                    </template>
                </TitleTips>
                <el-form slot="form" :inline="true" size="medium" label-width="120px" @submit.native.prevent>
                    <el-form-item label="清单子目编码">
                        <el-input v-model="form.listSubitemCode" placeholder="请输入" clearble></el-input>
                    </el-form-item>
                    <el-form-item label="清单子目名称">
                        <el-input v-model="form.listSubitemName" placeholder="请输入" clearble></el-input>
                    </el-form-item>
                    <el-form-item>
                        <BaseButton :disabled="chapterList.length === 0" @click="handleFilter">查询</BaseButton>
                        <BaseButton :disabled="chapterList.length === 0" type="second" @click="handleReset">重置</BaseButton>
                    </el-form-item>
                </el-form>

                <div slot="button">
                    <!-- 如果没有章次或者被锁定了，都禁止点击 -->
                    <BaseButton v-if="(type === 1 && premissionCode.has('dlyh_e29_f29_2')) || (type === 2 && premissionCode.has('dlyh_e30_f37_2'))" :disabled="chapterList.length === 0 || isLock" @click="handleAdd">新增子目</BaseButton>
                </div>

                <!--数据列表区-->
                <BaseTable
                    slot="table"
                    v-loading="listLoading"
                    :columns="columns"
                    :data="list"
                    row-key="id"
                    height="calc(100% - 73px)"
                    highlight-current-row
                    default-expand-all
                    :tree-props="{ children: 'childrenList', hasChildren: ''}"
                    @selection-change="handleSelectionChange"
                    @expand-change="handleExpandChange"
                >
                    <template #code="{ scope: { row } }">
                        <div class="icon-flex">
                            <IconSvg v-if="!row.expanded && row.expanded !== undefined && row.hasChildren === 1" icon-class="file" class="file-icon"></IconSvg>
                            <IconSvg v-if="(row.expanded || row.expanded === undefined) && row.hasChildren === 1" icon-class="file-open" class="file-icon"></IconSvg>
                            <IconSvg v-if="row.hasChildren === 2" icon-class="catalogue" class="catalogue-icon"></IconSvg>
                            {{ row.listSubitemCode }}
                        </div>
                    </template>
                    <template #handle="{ scope: { row } }">
                        <BaseButton v-if="(!isLock && type === 1 && premissionCode.has('dlyh_e29_f31_2')) || (!isLock && type === 2 && premissionCode.has('dlyh_e30_f39_2'))" type="text" @click="handleEdit(row)">编辑</BaseButton>
                        <BaseButton type="text" @click="checkoutLog(row.id)">日志</BaseButton>
                        <!-- 未锁定、存在下级、不超过10级，然后根据类型和按钮权限 显示按钮 -->
                        <BaseButton
                            v-if="!isLock && row.level < 10 && row.hasChildren === 1 && ((type === 1 && premissionCode.has('dlyh_e29_f30_2')) || (type === 2 && premissionCode.has('dlyh_e30_f38_2')))"
                            type="text"
                            @click="handleAdd(row)"
                        >新增子项</BaseButton>
                        <BaseButton v-if="!isLock && (!row.children || !row.children.length) && ((type === 1 && premissionCode.has('dlyh_e29_f32_2')) || (type === 2 && premissionCode.has('dlyh_e30_f40_2')))" type="text" color="danger" @click="handleDelete(row.id)">删除</BaseButton>
                    </template>
                </BaseTable>
                <!--分页组件-->
                <Pagination
                    slot="pagination"
                    :current-page.sync="page.pageNo"
                    :page-size.sync="page.pageSize"
                    :total="page.total"
                    @current-change="getList"
                    @size-change="getList"
                />
            </BasePage>
            <ChapterSetting ref="chapterDialog" @success="chapterUpdateSuccess"></ChapterSetting>
            <ChildSaveOrUpdate ref="childDialog" :type="type" @success="handleFilter"></ChildSaveOrUpdate>
            <ImportDialog ref="importDialog" :type="type" @success="importSuccess"></ImportDialog>
            <DeleteList ref="deleteListDialog" :type="type"></DeleteList>
            <OperationLog ref="logDialog" :type="type"></OperationLog>
        </div>
    </div>
    
</template>

<script>
import BasePage from '@/layouts/BasePage'
import { ProjectLedgerModel } from '@/models'
import { MaintenanceType2Options } from '@/views/auxiliary-decision/constants'
import reconfirm from '@/utils/reconfirm'
import ChapterSetting from './ChapterSetting.vue'
import ChildSaveOrUpdate from './ChildSaveOrUpdate.vue'
import ImportDialog from './ImportDialog.vue'
import DeleteList from './DeleteList.vue'
import OperationLog from './OperationLog.vue'
import { ProjectLedgerApi } from '@/api'
import { downLoadGet } from '@/utils/blob-download'

export default {
    name: 'SchemePriceList',
    components: {
        BasePage,
        ChapterSetting,
        ChildSaveOrUpdate,
        ImportDialog,
        DeleteList,
        OperationLog
    },
    props: {
        type: {
            type: Number,
            default: 1 // type=1:普通工程量清单；type=2:计日工
        },
        isLock: {
            type: Boolean,
            default: false
        },
        premissionCode: {
            default: () => new Map(),
            validator: function (value) {
                return value instanceof Map
            }
        }
    },
    data() {
        return {
            leftTitle: '章次',
            rightitle: '工程量清单子目',
            MaintenanceType2Options,
            chapterCode: '',
            schemeName: '',
            maintType: '',
            model: new ProjectLedgerModel(),
            chapterList: [],
            listLoading: false,
            schemeLoading: true,
            activeTitleName: '',
            form: {
                listSubitemCode: '',
                listSubitemName: ''
            },
            list: [],
            page: {
                pageNo: 1,
                pageSize: 10,
                total: 0
            },
            columns: [
                {
                    slot: 'code',
                    attrs: {
                        prop: 'listSubitemCode',
                        label: '清单子目编码',
                        'min-width': '190',
                        'class-name': 'custom-td'
                    }
                },
                {
                    attrs: {
                        prop: 'listSubitemName',
                        label: '清单子目名称',
                        width: '160',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'unitSymbol',
                        label: '单位',
                        width: '90',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'quantity',
                        label: '数量',
                        width: '120',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'price',
                        label: '单价（元）',
                        width: '140',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'amount',
                        label: '合价（元）',
                        width: '160',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'remark',
                        label: '备注',
                        width: '150',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'handle',
                    attrs: {
                        label: '操作',
                        width: '210',
                        fixed: 'right'
                    }
                }
            ],
            selectionList: [],
            id: '',
            totalAmount: '-',
            exportLoading: false
        }
    },
    // watch: {
    //     // 监听下锁定状态，锁定后把操作一列删除，后续日志功能完善后，锁定了也要显示日志，这段可以删除
    //     isLock(newValue) {
    //         if (newValue) {
    //             this.columns.pop()
    //         }
    //     }
    // },
    async created() {
        this.id = this.$route.query.id
        await this.getChapterList()
        this.initList()

        // 处理下名称
        if (this.type === 1) {
            this.leftTitle = '章次'
            this.rightitle = '工程量清单子目'
        }
        if (this.type === 2) {
            this.leftTitle = '分类'
            this.rightitle = '计日工清单子目'
        }
    },
    methods: {
        async importSuccess() {
            await this.getChapterList()
            if (this.chapterCode) {
                this.getList()
            } else {
                this.initList()
            }
        },
        handleExpandChange(row, expanded) {
            row.expanded = expanded
        },
        initList() {
            if (this.chapterList.length === 0) { return }
            const active = this.chapterList[0] || {}
            this.chapterCode = active.code
            this.activeTitleName = active.name
            this.getList()
        },
        handleChangeScheme(item) {
            this.chapterCode = item.code
            this.activeTitleName = item.name
            this.getList()
        },
        // 子目次列表
        getList() {
            console.log(this.id)
            this.listLoading = true
            this.model
                .quantitiesList({
                    msType: 2,
                    projectId: this.id,
                    type: this.type,
                    chapterSequenceCode: this.chapterCode,
                    ...this.page,
                    ...this.form})
                .then(res => {
                    this.list = res.list || []
                    this.page.total = res.totalCount
                    this.totalAmount = res.totalAmount
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        async chapterUpdateSuccess(data) {
            await this.getChapterList()
            this.initList()
        },
        // 章次列表
        getChapterList() {
            this.schemeLoading = true
            const data = {
                projectId: this.id,
                type: this.type,
                msType: 2
            }
            return this.model
                .chapterListById(data)
                .then(res => {
                    this.chapterList = (res || []).map(item => {
                        let name = ''
                        if (this.type === 1) {
                            name = item.listSubitemCode + '章 ' + item.listSubitemName
                        }
                        if (this.type === 2) {
                            name = item.listSubitemName
                        }
                        return {
                            name,
                            code: item.listSubitemCode,
                            id: item.id
                        }
                    })
                })
                .finally(() => {
                    this.schemeLoading = false
                })
        },
        // 查询
        handleReset() {
            this.form.listSubitemCode = ''
            this.form.listSubitemName = ''
            this.handleFilter()
        },
        // 查询
        handleFilter() {
            this.page.pageNo = 1
            this.getList()
        },
        handleSelectionChange(value) {
            this.selectionList = value
        },
        handleAddChapter() {
            const codes = this.chapterList.map(item => item.code)
            this.$refs['chapterDialog'].open(codes)
        },
        handleImport() {
            this.$refs['importDialog'].open({
                projectId: this.id,
            })
        },
        handleExport() {
            this.exportLoading = true
            const path = ProjectLedgerApi.quantitiesAndDayExportPath
            const params = {
                msType: 2,
                type: this.type,
                projectId: this.id,
            }
            downLoadGet(path, params, '', 'Excel', () => {
                this.exportLoading = false
            })
        },
        checkDeleteList() {
            this.$refs['deleteListDialog'].open({
                projectId: this.id,
                chapterName: this.activeTitleName,
            })
        },
        checkoutLog(id) {
            this.$refs['logDialog'].open({ id })
        },
        handleDeleteChapter(id, code) {
            reconfirm({
                text: '确定删除该章次？</br>删除后无法恢复，请谨慎操作！',
                type: 'error',
                dangerouslyUseHTMLString: true,
                callback: () => {
                    return this.model.chapterDelete({ ids: [id] }).then(async() => {
                        this.$message.success('删除成功!')
                        await this.getChapterList()
                        // 如果一个都没有了，清空下当前选中值
                        if (this.chapterList.length === 0) {
                            this.chapterCode = ''
                            this.activeTitleName = ''
                            return
                        }
                        // 如果删除的是当前选中数据，重置选中为第一条
                        if (code === this.chapterCode) {
                            this.initList()
                        }
                    })
                }
            })
        },
        handleAdd(row) {
            let parentCode = this.chapterCode
            let level = 1
            if (row.id) {
                parentCode = row.listSubitemCode
                level = row.level + 1
            }
            this.$refs['childDialog'].open({
                type: 'add',
                projectId: this.id,
                parentCode, // 100 200 这种
                parentName: row.listSubitemName || '',
                pName: this.activeTitleName, // 100 总则 已经拼接
                chapterSequenceCode: this.chapterCode, // 章次编码
                level
            })
        },
        
        handleEdit(row) {
            this.$refs['childDialog'].open({
                row,
                type: 'edit',
                projectId: this.id,
                parentCode: row.parentCode || this.chapterCode, // 一级的子目后端没返回parentCode
                parentName: row.parentName || '',
                pName: this.activeTitleName,
                chapterSequenceCode: this.chapterCode,
                level: row.level
            })
        },
        handleDelete(id) {
            reconfirm({
                text: '确定删除该子目？</br>删除后无法恢复，请谨慎操作！',
                type: 'error',
                dangerouslyUseHTMLString: true,
                callback: () => {
                    return this.model.deleteChild({ ids: [id] }).then(() => {
                        this.getList()
                        this.$message.success('删除成功!')
                    })
                }
            })
        },
    },

}
</script>

<style lang="scss" scoped>
.bill-of-quantities {
    height: calc(100% - 48px);
    .handle-button {
        padding: 8px 12px;
        text-align: right;
    }
}
.bill-of-quantities-content {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    .no-data {
        color: #9090A0;
        font-size: 14px;
        text-align: center;
        padding: 100px 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        .icon {
            font-size: 66px;
            padding-bottom: 12px;
            color: #c2c2c2;
        }
        .button {
            color: #0162FF;
            font-style: normal;
            cursor: pointer;
        }
    }
    .left {
        width: 330px;
        height: 100%;
        margin-right: 16px;
        flex-shrink: 0;
        border: 1px solid #f0f4f7;
        box-shadow: 0px 0px 4px 0px rgba(131, 145, 178, 0.14);
        padding: 24px 16px;
        .list {
            border-bottom: 1px solid #f0f4f7;
            overflow-y: auto;
            overflow-x: hidden;
            max-height: 100%;
            margin-bottom: 16px;
            .item {
                border-top: 1px solid #f0f4f7;
                padding: 0 8px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 14px;
                line-height: 42px;
                cursor: pointer;
                &:hover,
                &.active {
                    background-color: rgba(0, 98, 255, 0.06);
                    color: #0162FF;
                }
                .btn {
                    display: none;
                    flex-shrink: 0;
                }
                &:hover .btn {
                    display: block;
                }
            }
        }
    }
    .title-item {
        margin-left: 32px;
    }

    /* 替换默认展开收起图片 */
    ::v-deep {
        .el-table__expand-icon {
            width: 16px;
            height: 16px;
            background: url("~@/assets/images/zhankai.png") no-repeat;
            background-size: 100% 100%;
            margin-left: -20px;
            flex-shrink: 0;
            .el-icon-arrow-right {
                display: none;
            }
        }
        .el-table__expand-icon--expanded {
            transform: none;
            background: url("~@/assets/images/shouqi.png") no-repeat;
            background-size: 100% 100%;
            flex-shrink: 0;
        }
        .custom-td .cell {
            display: flex;
            align-items: center;
        }
    }
    .icon-flex {
        display: flex;
        align-items: center;
        line-height: 1.5;

        .file-icon {
            width: 22px;
            font-size: 22px;
            margin-right: 4px;
            flex-shrink: 0;
        }
        .catalogue-icon {
            width: 20px;
            font-size: 18px;
            margin-right: 4px;
            flex-shrink: 0;
        }
    }
}
.golobal-button {
    margin: 8px 12px;
    text-align: right;
}

</style>
